package com.sin.j2me.wihd.window;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import com.sin.j2me.framework.NewDebug;
import com.sin.j2me.framework.SinUtil;
import com.sin.j2me.util.ArrayList;
import com.sin.j2me.util.AsynchTask;
import com.sin.j2me.wihd.FrameWork;
import com.sin.j2me.wihd.common.Commands;
import com.sin.j2me.wihd.common.Constant;
import com.sin.j2me.wihd.common.Protocol;
import com.sin.j2me.wihd.common.Strings;
import com.sin.j2me.wihd.communi.InterfaceRequest;
import com.sin.j2me.wihd.model.Param;
import com.sin.j2me.wihd.model.Response;
import com.sin.j2me.wihd.model.Thing;

public class ThingsWindow extends Window implements CommandListener {
	private List list = null;
	private ArrayList things = null;
	public ThingsWindow() {
		things = new ArrayList();
		list = new List(Strings.mythings, List.IMPLICIT);
		
		list.addCommand(Commands.add);
		list.addCommand(Commands.del);
		list.addCommand(Commands.back);
		list.addCommand(Commands.exit);
		list.setSelectCommand(Commands.mod);
		list.setCommandListener(this);
	}
	
	public Displayable getWindow() {
		return list;
	}
	
	private int t_thingid;
	private String t_dir;
	private int t_count;
	private boolean t_head;
	private void getThing(int thingid, String dir, int count, boolean head){
		if(locked){
			NewDebug.i(Strings.I_LOCKED);
			return;
		}
		lock();
		t_thingid = thingid;
		t_dir = dir;
		t_count = count;
		t_head = head;
		new AsynchTask(new Runnable() {
			
			public void run() {
				Param param = new Param();
				param.addPam(Protocol.P_COUNT, ""+t_count);
				param.addPam(Protocol.P_THINGID, ""+t_thingid);
				param.addPam(Protocol.P_DIR, t_dir);
				addFromResponse(InterfaceRequest.getResponse(Protocol.I_GETTHINGS, param));
				unlock();
			}
		});
	}
	
	public void getLatestThings(){
		this.deleteAllThing();
		getThing(1, Protocol.V_LATEST, Constant.COUNT_DEFAULT, false);
	}
	
	private void getDownThing() {
		if(this.things.size() == 0){
			getLatestThings();
		}
		else{
			Thing thing = (Thing) this.things.get(this.things.size()-1);
			getThing(thing.getThingid(), Protocol.V_DOWN, Constant.COUNT_DEFAULT, false);
		}
	}
	
	public void addThing(Thing thing, boolean head){
		String title = getLabel(thing);
		Image image = getImage(thing);
		if(head){
			this.list.insert(0, title, image);
			things.insert(thing, 0);
		}
		else{
			this.list.append(title, image);
			things.add(thing);
		}
	}
	
	private void deleteAllThing(){
		this.list.deleteAll();
		this.things.clear();
	}
	
	private void deleteThing(int ix){
		this.list.delete(ix);
		this.things.delete(ix);
	}
	
	private void addFromResponse(Response response){
		if(response.isOk()){
			JSONArray items  = (JSONArray) response.get(Protocol.P_ITEMS);
			try{
				for(int i=0; i<items.length(); ++i){
					JSONObject itm = (JSONObject) items.get(i);
					String status = itm.getString(Protocol.P_STATUS);
					int userid = Integer.parseInt(itm.getString(Protocol.P_USERID));
					int thingid = Integer.parseInt(itm.getString(Protocol.P_THINGID));
					String detail = itm.getString(Protocol.P_DETAIL);
					String time = itm.getString(Protocol.P_TIME);
					String title = itm.getString(Protocol.P_TITLE);
					Thing thing = new Thing(thingid, userid, title, status, detail, time);
					addThing(thing, t_head);
				}
				if(items.length() == t_count){
					Thing more = new Thing();
					more.setTitle(Strings.more);
					addThing(more , false);
				}
			}
			catch(JSONException e){
				e.printStackTrace();
			}
		}
		else if(response.getStatus() == Response.FAIL){
			setNotice(response.getString(Protocol.R_INFO));
		}
		else{
			setNotice(Strings.P_NETWORKERR);
		}
	}
	
	private void getMore(){
		// get more
		this.deleteThing(this.list.size()-1);
		getDownThing();
	}
	
	private Thing sel = null;
	
	public void commandAction(Command cmd, Displayable dis) {
		System.out.println("Cmd:" + cmd.getLabel());
		if(cmd == Commands.exit){
			FrameWork.exit();
		}
		else if(cmd == Commands.back){
			FrameWork.finishWindow(this);
		}
		else if(cmd == Commands.mod){
			if(list.getSelectedIndex()<0)
				return;
			sel = (Thing) things.get(list.getSelectedIndex());
			if(sel.getThingid() == 0){
				// get more
				getMore();
			}
			else{
				FrameWork.detailWindow.startWith(sel, DetailWindow.MOD);
			}
		}
		else if(cmd == Commands.add){
			// add thing
			FrameWork.detailWindow.startWith(new Thing(), DetailWindow.ADD);
		}
		else if(cmd == Commands.del){
			// delete
			if(list.getSelectedIndex()<0)
				return;
			sel = (Thing) things.get(list.getSelectedIndex());
			if(sel.getThingid() != 0){
				if(locked){
					setNotice(Strings.I_LOCKED);
					return;
				}
				lock();
				new AsynchTask(new Runnable() {
					public void run() {
						Param param = new Param();
						param.addPam(Protocol.P_THINGID, ""+sel.getThingid());
						Response response = InterfaceRequest.getResponse(Protocol.I_DELTHING, param);
						if(response.isOk()){
							deleteThing(getItemIndex(sel));
							setNotice(Strings.N_DELOK);
						}
						else if(response.getStatus() == Response.FAIL){
							setNotice(response.getString(Protocol.R_INFO));
						}
						else{
							setNotice(Strings.P_NETWORKERR);
						}
						unlock();
					}
				});
				
			}
		}
	}
	private String getLabel(Thing thing){
		if(thing.getThingid() == 0){
			return "<--get more-->";
		}
		else{
			String dttm = SinUtil.date2String(SinUtil.string2Date(thing.getTime()));
			String md = dttm.substring(dttm.indexOf('-')+1, dttm.indexOf(' '));
			return md + " " + thing.getTitle();
		}
	}
	private Image getImage(Thing thing){
		return null;
	}
	private int getItemIndex(Thing thing){
		for(int i=0; i<this.things.size(); ++i){
			if(this.things.get(i) == thing)
				return i;
		}
		return -1;
	}
	public void refreshItem(int ix){
		this.list.delete(ix);
		Thing thing = (Thing) this.things.get(ix);
		this.list.insert(ix, getLabel(thing), getImage(thing));
	}
	public void refreshItem(Thing thing){
		if(thing != null){
			int ix = getItemIndex(thing);
			if(ix>=0){
				refreshItem(ix);
			}
		}
	}
}
